import { NAutoComplete } from "naive-ui";
import type {
  AutoCompleteProps,
  AutoCompleteDefaultSlotProps,
  AutoCompleteInst,
} from "naive-ui";
import type { BaseComponentType, OmitHTMLAttributes } from "../types";
import { getSlotsDom } from "../utils";
export type AutoCompleteFactoryConstructorType = {
  props?: AutoCompleteProps;
  attrs?: OmitHTMLAttributes<"onInput">;
  defaultSlot?:
    | ((options: AutoCompleteDefaultSlotProps) => BaseComponentType)
    | null;
  emptySlot?: BaseComponentType;
  prefixSlot?: BaseComponentType;
  suffixSlot?: BaseComponentType;
};
export class AutoCompleteFactory {
  private attrs: OmitHTMLAttributes<"onInput"> = {};
  private props: AutoCompleteProps = {};
  private defaultSlot:
    | ((options: AutoCompleteDefaultSlotProps) => BaseComponentType)
    | null = null;

  private emptySlot: BaseComponentType = null;
  private prefixSlot: BaseComponentType = null;
  private suffixSlot: BaseComponentType = null;
  private domRef: AutoCompleteInst | null = null;

  constructor(data?: AutoCompleteFactoryConstructorType) {
    if (data?.props) this.setProps(data.props);
    if (data?.attrs) this.setAttrs(data.attrs);
    if (data?.defaultSlot) this.setDefault(data.defaultSlot);
    if (data?.emptySlot) this.setEmpty(data.emptySlot);
    if (data?.prefixSlot) this.setPrefix(data.prefixSlot);
    if (data?.suffixSlot) this.setSuffix(data.suffixSlot);
  }
  setAttrs(attrs: OmitHTMLAttributes<"onInput">) {
    this.attrs = attrs;
    return this;
  }
  setProps(props: AutoCompleteProps) {
    this.props = props;
    return this;
  }

  setDefault(
    component: (options: AutoCompleteDefaultSlotProps) => BaseComponentType
  ) {
    this.defaultSlot = component;
    return this;
  }
  setPrefix(component: BaseComponentType) {
    this.prefixSlot = component;
    return this;
  }
  setSuffix(component: BaseComponentType) {
    this.suffixSlot = component;
    return this;
  }
  setEmpty(component: BaseComponentType) {
    this.emptySlot = component;
    return this;
  }

  blur() {
    this.domRef?.blur();
  }

  focus() {
    this.domRef?.focus();
  }

  create() {
    return (
      <NAutoComplete
        ref={(el: HTMLElement) => {
          this.domRef = el as unknown as AutoCompleteInst;
        }}
        {...this.attrs}
        {...this.props}
      >
        {{
          default: this.defaultSlot
            ? (options: AutoCompleteDefaultSlotProps) =>
                this.defaultSlot ? getSlotsDom(this.defaultSlot(options)) : null
            : null,
          empty: () => getSlotsDom(this.emptySlot),
          prefix: () => getSlotsDom(this.prefixSlot),
          suffix: () => getSlotsDom(this.suffixSlot),
        }}
      </NAutoComplete>
    );
  }
}
